package com.xxxx.server.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.xxxx.server.pojo.vo.MyFilePath;
import com.xzl.tool.util.MyException;
import com.xzl.tool.util.RespBean;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponses;
import net.lingala.zip4j.core.ZipFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    @Value("${spring.tengxun.accessKey}")
    private String accessKey;
    @Value("${spring.tengxun.secretKey}")
    private String secretKey;
    @Value("${spring.tengxun.bucket}")
    private String bucket;
    @Value("${spring.tengxun.bucketName}")
    private String bucketName;
    @Value("${spring.tengxun.path}")
    private String path;
    @Value("${spring.tengxun.qianzui}")
    private String qianzui;

    /**
     * 上传道腾讯云服务器（https://cloud.tencent.com/document/product/436/10199）
     *
     * @return
     */
    @PostMapping(value = "/")
    @ResponseBody
    public RespBean Upload(@RequestParam(value = "file") MultipartFile file) {
        if (file == null) {
            return RespBean.error("文件为空");
        }
        String oldFileName = file.getOriginalFilename();
        String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + eName;
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DATE);
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(bucket));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        String bucketName = this.bucketName;

        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        File localFile = null;
        try {
            localFile = File.createTempFile("temp", null);
            file.transferTo(localFile);
            // 指定要上传到 COS 上的路径
            String key = "/" + this.qianzui + "/" + year + "/" + month + "/" + day + "/" + newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            return RespBean.success("上传成功",this.path + putObjectRequest.getKey());
        } catch (IOException e) {
            return RespBean.error(e.getMessage());
        } finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }
    }
    @PostMapping({"/doUpload"})
    @ApiOperation("文件上传(不需要token令牌)")
    @ApiResponses({@io.swagger.annotations.ApiResponse(code=200, message="请求成功,返回结果result:{filename 文件名},{base64 base64编码}"), @io.swagger.annotations.ApiResponse(code=400, message="请求失败")})
    public Map<String, Object> doUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null) {
            return new HashMap(0);
        }

        Map map = new HashMap(2);

        // 原文件名称
        String filename = file.getOriginalFilename();

        // 创建临时文件
        File tempFile = File.createTempFile("tem", null);
        file.transferTo(tempFile);
        tempFile.deleteOnExit();

        // 文件输入流
        FileInputStream inputStream = new FileInputStream(tempFile);

        byte[] buffer = new byte[(int)tempFile.length()];
        inputStream.read(buffer);
        inputStream.close();

        // 转换为base64编码格式
        String base64 = new sun.misc.BASE64Encoder().encode(buffer);

        // 上面方法中获得的base64编码中，包含有换行符，统一全部替换掉
        base64 = base64.replaceAll("[\\s*\t\n\r]", "");

        // 返回值
        map.put("filename", filename);
        map.put("base64", base64);

        return map;
    }


}
